import urllib.parse
import requests
import urllib.request
import socket
import json


class Robot:
    def __init__(self):
        self.msg = ''

    def ai_talk(self):
        msg = self.msg
        def qykApi(msg):
            base_url = 'http://api.qingyunke.com/api.php?key=free&appid=0&' # 青云客智能聊天api
            data = {
                'msg': msg['raw_message']
            }
            new_data = urllib.parse.urlencode(data)
            url = base_url + new_data
            response = urllib.request.urlopen(url).read().decode('utf-8')
            response_msg = eval(response)['content'].replace('{br}', '\n')
            return response_msg

        if self.msg['message_type'] == 'private':
            return self.sdMsg(qykApi(msg), self.msg['user_id'], 'private')
        else:
            return False

    # ----------------------------------------------------
    # 接收消息函数 需要循环执行，返回值字典格式
    def revMsg(self):  # json or None
        ListenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ListenSocket.bind(('localhost', 5701))
        ListenSocket.listen(100)

        HttpResponseHeader = '''HTTP/1.1 200 OK
        Content-Type: text/html
        '''
        Client, Address = ListenSocket.accept()

        def request2json(msg):
            for i in range(len(msg)):
                if msg[i] == "{" and msg[-2] == "}":
                    return json.loads(msg[i:])
            return None

        try:
            Request = Client.recv(1024).decode(encoding='utf-8')
            rev_json = request2json(Request)
            Client.sendall(HttpResponseHeader.encode(encoding='utf-8'))
            Client.close()
            self.msg = rev_json
        except:
            pass
        return rev_json

    def sdMsg(self, msg, qq_id, msg_type):
        if msg_type == "private":
            data = {
                'user_id': qq_id,
                'message': msg,
                'auto_escape': False
            }
            cq_url = "http://127.0.0.1:5700/send_private_msg"
            rev = requests.post(cq_url, data=data)
        elif msg_type == "group":
            data = {
                'group_id': qq_id,
                'message': msg,
                'auto_escape': False
            }
            cq_url = "http://127.0.0.1:5700/send_group_msg"
            rev = requests.post(cq_url, data=data)
        else:
            return False
        if rev.json()['status'] == 'ok':
            return True
        return False